<template>
  <ele-modal
    :width="550"
    :visible="visible"
    :confirm-loading="loading"
    :title="'新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      :label-col="{ md: { span: 5 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-row :gutter="24">
        <a-col :md="24" :sm="24" :xs="24">
          <a-form-item label="经营品牌" v-bind="validateInfos.name">
            <a-input
              allow-clear
              placeholder="请输入"
              v-model:value="form.name"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="排序">
            <a-input
              allow-clear
              placeholder="请输入"
              v-model:value="form.sort"
              autocomplete="off"
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-switch v-model:checked="checked" @change="change" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { detail, edit } from '@/api/material/brand';
  // 表格列配置
  const useForm = Form.useForm;

  const emit = defineEmits(['done', 'update:visible']);

  const props = defineProps({
    // 弹窗是否打开
    visible: Boolean,
    editId: [String, Number]
  });

  // 提交状态
  const loading = ref(false);
  const checked = ref(true);

  onMounted(() => {
    form.id = props.editId;
    detail({ id: props.editId }).then((res) => {
      form.name = res.data.name;
      form.sort = res.data.sort;
      form.status = res.data.status;
      checked.value = res.data.status == 1 ? true : false;
    });
  });

  // 表单数据
  const form = reactive({
    id: '',
    name: '',
    sort: '',
    status: 1
  });

  const change = (e) => {
    form.status = e ? '1' : '0';
  };

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入经营品牌',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  const { validate, validateInfos } = useForm(form, rules);

  /* 保存*/
  const save = () => {
    validate()
      .then(() => {
        edit(form)
          .then((res) => {
            message.success(res.msg);
            emit('done');
          })
          .catch((e) => {
            message.error(e);
          });
      })
      .catch(() => {});
  };
  /* 更新visible */
  const updateVisible = (value) => {
    emit('update:visible', value);
  };
</script>
<style scoped></style>
